#============================================================
# Create Time:			2019-08-05 20:45:32
# Last modify:			2020-06-19 19:28:46
# Writer:				Wenhao	1795902848@qq.com
# File Name:			BooksWork.py
# File Type:			PY Source File
# Tool:					Mac -- vim & python
# Information:          将下载的书籍整理，并拷贝至Kindle中
#============================================================
#coding=utf-8
import re
import os
import shutil
from collections import Counter

#如果代码有bug，有可能误删掉自己，所以运行前先拷贝自己。
shutil.copy('BooksWork.py', '/Users/apple/Documents/Coding/Python/')

print('程序开始')
src_path = '/Users/apple/Documents/书籍/'
dst_path = '/Volumes/Kindle/documents/我的书籍/'

def valid_book_name(name):
    try:
        file_type = re.search('\.(\w*?)$', name).group(1)
        return file_type in ['mobi', 'txt', 'pdf']
    except:
        return False

#递归遍历当前文件夹
for r, d, f in os.walk('.'):
    #只处理文件夹中文件
    if(r.startswith('./')):
        for each in f:
            #将.mobi文件移动到当前目录
            if(valid_book_name(each)):
                path = os.path.join(r, each)
                shutil.move(path, src_path)

#删除不需要的文件夹，以及其中的文件
#删除完毕后，本文件夹中便不存在文件夹
for f in os.listdir(src_path):
    if(os.path.isdir(f)):
        shutil.rmtree(f)

books_src = [f for f in os.listdir(src_path) if valid_book_name(f)]

#有可能有多本书的不同格式同时存在。删掉多余的，只保留大小最小的。
books_without_post_fix = [re.search('(.*)\.\w*', book).group(1) for book in books_src]
counter = Counter(books_without_post_fix)
counter = {name:times for name, times in counter.items() if times > 1}
for name in counter.keys():
    books_rep = [(book, os.path.getsize(book)) for book in books_src if book.startswith(name)]
    min_book = min(books_rep, key=lambda x : x[1])
    books_rep.remove(min_book)
    for book_rep in books_rep:
        os.remove(book_rep[0])

books_src = [f for f in os.listdir(src_path) if valid_book_name(f)]

#去除书籍名称前面的时间戳
for book in books_src:
    prefix, name = re.search('(\d+?-\d+\s*)?(.*)', book).groups()
    #只给有时间戳的文件更名
    if(prefix != None):
        #使用move，保证目录中不会有重复书籍
        shutil.move(book, name)

#开始导入书籍
try:
    books_src = set(f for f in os.listdir(src_path) if valid_book_name(f))
    books_dst = set(f for f in os.listdir(dst_path) if valid_book_name(f))
    books = books_src - books_dst
    #将待导入书籍拷贝至Kindle相应目录
    print('目标文件夹是', dst_path)
    for i, book in enumerate(books):
        shutil.copy(book, dst_path)
        print('\t%d. 成功拷贝%s 至目标文件夹'%(i+1, book))
    if(len(books) == 0):
        print('当前文件夹的书籍都已经在目标文件夹啦!')
    else:
        print('整理书籍完毕, 共整理%d本书'%(len(books)))
except FileNotFoundError:
    print('检查Kindle是否与计算机连接')
